package com.tanhua.dubbo.api;

import com.tanhua.dubbo.api.mongo.OptionApi;
import com.tanhua.model.mongo.Answer;
import com.tanhua.model.mongo.Option;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;
import java.util.stream.Collectors;

@DubboService
public class OptionApiImpl implements OptionApi {

    @Autowired
    private MongoTemplate mongoTemplate;


    /**
     * @param answerList
     * @return
     */
    @Override
    public double countScore(List<Answer> answerList) {
        List<String> optionIds = answerList.stream().map(Answer::getOptionId).collect(Collectors.toList());
        Query query = new Query(Criteria.where("id").in(optionIds));
        List<Option> options = mongoTemplate.find(query, Option.class);
        double sum = 0d;
        for (Option option : options) {
            sum += option.getScore();
        }
        return sum;
    }

    /**
     * 查询分数
     *
     * @return
     * @param optionIds
     */
    @Override
    public List<Double> findScore(List<ObjectId> optionIds) {
        Query query = new Query(Criteria.where("id").in(optionIds));
        List<Option> options = mongoTemplate.find(query, Option.class);
        List<Double> result = options.stream().map(Option::getScore).collect(Collectors.toList());
        return result;
    }
}
